package com.ys.service.storage.impl;
import java.util.Date;
import com.alibaba.fastjson.JSON;
import com.ys.entity.business.TpAmazonShop;
import com.ys.entity.business.TpShopRegisterPhaseSet;
import com.ys.entity.finance.TcwAccountDetailedForCompany;
import com.ys.entity.storage.TccLogisticsMethod;
import com.ys.entity.storage.TccFbaPlan;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.entity.storage.*;
import com.ys.entity.sys.TsUserChange;
import com.ys.enume.finance.TcwOperateFrozenRunningEnum;
import com.ys.enume.storage.*;
import com.ys.mapper.storage.*;
import com.ys.service.business.TcwAccountDetailedForCompanyService;
import com.ys.service.finance.TcwAccountCountForCompanyService;
import com.ys.service.storage.FbaInboundApiService;
import com.ys.service.storage.TccFbaDeliverService;
import com.ys.service.storage.TccStockControlService;
import com.ys.service.sys.CommonApiService;
import com.ys.util.FbaUtils;
import com.ys.util.shiro.BeanUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: fxz
 * @CreateTime: 2024-12-30
 * @Description: FBA发货单实现层
 * @Version: 1.5
 */
@Service("tccFbaDeliverService")
public class TccFbaDeliverServiceImpl implements TccFbaDeliverService {

    private static final Logger logger = LoggerFactory.getLogger(TccFbaDeliverServiceImpl.class);

    @Autowired
    private FbaInboundApiService fbaInboundApiService;

    @Autowired
    private TccFbaDeliverMapper tccFbaDeliverMapper;

    @Autowired
    private CommonApiService<TccFbaDeliver> commonApiService;

    @Autowired
    private TccFbaDeliverItemMapper tccFbaDeliverItemMapper;

    @Autowired
    private TccStockControlService tccStockControlService;

    @Autowired
    private TccFbaLogisticsMethodMapper tccFbaLogisticsMethodMapper;

    @Autowired
    private TccFbaFeeDetailsMapper tccFbaFeeDetailsMapper;

    @Autowired
    private TcwAccountDetailedForCompanyService tcwAccountDetailedForCompanyService;

    @Autowired
    private TcwAccountCountForCompanyService tcwAccountCountForCompanyService;

    @Autowired
    private TccFbaDeliverSonMapper tccFbaDeliverSonMapper;

    @Autowired
    private StorageMapper storageMapper;

    @Autowired
    private TccLogisticsComprehensiveMapper tccLogisticsComprehensiveMapper;


    /**
     * 箱标打印
     * @param params
     * @return
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R printing(@RequestParam Map<String, Object> params) {
        if (params == null){
            return R.error("选择数据不允许为空!");
        }
        if (params.get("list") == null) {
            return R.error("选择数据不能为空!");
        }
        String[] strs = params.get("list").toString().split(",");
        Set<Long> idList = new HashSet<>();
        for(String id : strs){
            idList.add(Long.valueOf(id));
        }

        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject;
        for (Long id : idList) {
            TccFbaDeliver tccFbaDeliver = new TccFbaDeliver().setId(id).queryFirst();
            Integer count = new TccLogisticsComprehensive().setFbaDeliverBid(tccFbaDeliver.getBid()).where("A.status > 0").count();

            List<TccFbaDeliverItem> tccFbaDeliverItemList = new TccFbaDeliverItem().setPbid(tccFbaDeliver.getBid()).queryList();
            for (TccFbaDeliverItem tccFbaDeliverItem : tccFbaDeliverItemList) {
                if (count == 0) {
                    TccFbaBoxUpInfo tccFbaBoxUpInfo = new TccFbaBoxUpInfo().setId(tccFbaDeliverItem.getFbaBoxUpInfoId()).queryFirst();
                    //生成物流计划单
                    TccLogisticsComprehensive tccLogisticsComprehensive = new TccLogisticsComprehensive();
                    tccLogisticsComprehensive.setLogInvoiceBox(0);
                    tccLogisticsComprehensive.setLogOrderProfit(new BigDecimal("0"));
                    tccLogisticsComprehensive.setLogOrderProfitMargin(new BigDecimal("0"));
                    tccLogisticsComprehensive.setLogInvoiceWeight(new BigDecimal("0"));
                    tccLogisticsComprehensive.setLogInvoiceCost(new BigDecimal("0"));
                    tccLogisticsComprehensive.setLogInvoiceSalesFee(new BigDecimal("0"));
                    tccLogisticsComprehensive.setSpLogsticsFee(new BigDecimal("0"));
                    tccLogisticsComprehensive.setLogOrderProfitDz(new BigDecimal("0"));
                    tccLogisticsComprehensive.setLogServiceProfitDz(new BigDecimal("0"));
                    tccLogisticsComprehensive.setLogOrderMarginDz(new BigDecimal("0"));
                    tccLogisticsComprehensive.setLogServiceMarginDz(new BigDecimal("0"));
                    tccLogisticsComprehensive.setLogOrderStatusDz(TccLogisticsComprehensiveEnum.LogOrderStatusDz.EMPTY.value);
                    tccLogisticsComprehensive.setLogSpAmount(new BigDecimal("0"));
                    //物流付款状态
                    tccLogisticsComprehensive.setLogPayStatusZf(TccLogisticsComprehensiveEnum.LogPayStatusZf.EMPTY.value);
                    tccLogisticsComprehensive.setServiceTariff(new BigDecimal("0"));
                    tccLogisticsComprehensive.setRateDuty(new BigDecimal("0"));
                    tccLogisticsComprehensive.setSpTariffAmount(new BigDecimal("0"));
                    //关税付款状态
                    tccLogisticsComprehensive.setTariffPayStatus(TccLogisticsComprehensiveEnum.TariffPayStatus.EMPTY.value);
                    //关税支付状态
                    tccLogisticsComprehensive.setTariffZfStatus(TccLogisticsComprehensiveEnum.TariffZfStatus.EMPTY.value);

                    tccLogisticsComprehensive.setStatus(TccLogisticsComprehensiveEnum.Status.EMPTY.value);
                    tccLogisticsComprehensive.setCreateTime(new Date());
                    tccLogisticsComprehensive.setFbaDeliverBid(tccFbaDeliver.getBid());
                    tccLogisticsComprehensive.setFbaDeliverId(tccFbaDeliver.getId());
                    tccLogisticsComprehensive.setFbaBoxUpBid(tccFbaDeliverItem.getFbaBoxUpBid());
                    tccLogisticsComprehensive.setFbaPlanBid(tccFbaDeliver.getFbaPlanBid());
                    tccLogisticsComprehensive.setFbaDeliverItemId(tccFbaDeliverItem.getId());
                    tccLogisticsComprehensive.setFbaNo(tccFbaBoxUpInfo.getFbaNo());
                    tccLogisticsComprehensiveMapper.insert(tccLogisticsComprehensive);
                }
                R r = fbaInboundApiService.getLabels(tccFbaDeliver, tccFbaDeliverItem);
                if (r.getCode() != 0) {
                    return R.error(r.getMsg());
                }
                jsonObject = new JSONObject();
                JSONObject getLabelsJob = JSONObject.parseObject(r.get("data").toString());

                jsonObject.put("data", getLabelsJob.get("downloadURL"));
                jsonObject.put("dataOther", getLabelsJob.get("labelsPDF"));
                jsonArray.add(jsonObject);
            }
            if (tccFbaDeliver.getStatus() == TccFbaDeliverEnum.Status.TRANSSHIPPED.value) {
                tccFbaDeliver.setStatus(TccFbaDeliverEnum.Status.READYSHIPMENT.value);
                tccFbaDeliverMapper.update(tccFbaDeliver);
            }
        }
        return R.ok(jsonArray);
    }

    /**
     * 计划取消
     * @param id
     * @return
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R delete(Long id,int type) throws Exception {
//        if (id == null){
//            return R.error("选择数据不允许为空!");
//        }
//        TccFbaDeliver tccFbaDeliver = new TccFbaDeliver().setId(id).queryFirst();
//        if (tccFbaDeliver == null){
//            return R.error("该发货单不存在!");
//        }
//        if (type == 0){
//            if (tccFbaDeliver.getStatus() != TccFbaDeliverEnum.Status.NOTRANSSHIPPED.value){
//                return R.error("FBA发货单货件状态只允许待转运计划取消,请核实数据!");
//            }
//        }else {
//            if (tccFbaDeliver.getStatus() != TccFbaDeliverEnum.Status.TRANSSHIPPED.value){
//                return R.error("FBA发货单货件状态只允许待转运计划取消,请核实数据!");
//            }
//        }
//
//        List<TccFbaDeliver> tccFbaDeliverList = new TccFbaDeliver().setFbaPlanBid(tccFbaDeliver.getFbaPlanBid()).queryList();
//        Integer status = 0;
//        if (type == 0){
//            status = TccFbaDeliverEnum.Status.CANCEL.value;
//        }else {
//            status = TccFbaDeliverEnum.Status.COMPLETECANCEL.value;
//        }
//        for (TccFbaDeliver tccFbaDeliver1 : tccFbaDeliverList){
//            tccFbaDeliver1.setStatus(status);
//            tccFbaDeliverMapper.update(tccFbaDeliver1);
//        }
//
//        //修改所有装箱单的信息
//        List<TccFbaBoxUp> tccFbaBoxUpList = new TccFbaBoxUp().setBidFbaPlan(tccFbaDeliver.getFbaPlanBid()).queryList();
//
//        List<TccFbaCancelItemByAdd> cancelItemList = new ArrayList<>();
//        for (TccFbaBoxUp tccFbaBoxUp : tccFbaBoxUpList){
//            if (tccFbaBoxUp.getBoxState() == TccFbaBoxUpEnum.BoxState.YES_CANCEL.value){
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                return R.error("该装箱单:"+tccFbaBoxUp.getBid()+"已取消,请核实数据");
//            }
//            tccFbaBoxUp.setBoxState(TccFbaBoxUpEnum.BoxState.YES_CANCEL.value);
//            tccFbaBoxUpMapper.update(tccFbaBoxUp);
//
//            Integer shipmentState = null;
//            if (type == 0){
//                //待转运
//                shipmentState = TccFbaCancelEnum.ShipmentState.WAIT_TRANSPORT.value;
//            }else {
//                //已转运
//                shipmentState = TccFbaCancelEnum.ShipmentState.YES_FINISHED.value;
//            }
//
//            //生成计划取消单
//            if (shipmentState != null){
//                TccFbaCancelItemByAdd tccFbaCancelItemByAdd = new TccFbaCancelItemByAdd();
//                tccFbaCancelItemByAdd.setShipmentState(shipmentState);
//                tccFbaCancelItemByAdd.setBidFbaBoxUp(tccFbaBoxUp.getBid());
//                tccFbaCancelItemByAdd.setBidFbaDelivery(tccFbaDeliver.getBid());
//                cancelItemList.add(tccFbaCancelItemByAdd);
//            }
//        }
//
//        //TODO 生成计划取消单
////        R r = tccFbaCancelService.addCancel(tccFbaDeliver.getFbaPlanBid(),cancelItemList);
////        if (r.getCode() != 0){
////            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
////            return R.error(r.getMsg());
////        }
//        //fba计划单
//        TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(tccFbaDeliver.getFbaPlanBid()).queryFirst();
//        if (tccFbaPlan.getStatus() == TccFbaPlanEnum.Status.CANCELED.value){
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return R.error("该计划单:"+tccFbaPlan.getBid()+"已取消,请核实数据");
//        }
//        tccFbaPlan.setStatus(TccFbaPlanEnum.Status.CANCELED.value);
//        tccFbaPlanMapper.update(tccFbaPlan);

        return R.ok("计划取消成功!");
    }


    /**
     * 转运审核
     * @param params
     * @return
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R flow(@RequestParam Map<String, Object> params) throws Exception {
        try {

            if (params.get("choooseDatas") == null) {
                return R.error("参数不存在,请核实再操作!");
            }
            JSONArray detailJA = JSON.parseArray(params.get("choooseDatas").toString());
            Set<String> fbaplanList = new HashSet<>();
            for (int i = 0; i < detailJA.size(); i++) {
                JSONObject JO = detailJA.getJSONObject(i);
                String fbaplanBid = JO.getString("fbaplanBid");
                fbaplanList.add(fbaplanBid);
            }
            for (String bid : fbaplanList) {
                //整个计划单审核
                TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(bid).queryFirst();
                if (tccFbaPlan.getStatus() != TccFbaPlanEnum.Status.ISAUDITED.value) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error("该计划单:" + tccFbaPlan.getBid() + "状态不是已审核不允许转运审核,请核实数据");
                }

                if (tccFbaPlan.getCreationMethod() == 1) {//自动
                    //查询是否追踪编号获取完全
                    Integer count = new TccFbaBoxUpInfo().setBidFbaPlan(tccFbaPlan.getBid()).where("A.FbaTrackNo IS NULL").count();
                    if (count > 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return R.error("该计划单:" + tccFbaPlan.getBid() + "API还有未获取到追踪编码,请等待10分钟后再操作!");
                    }
                }


                //店铺信息
                TpAmazonShop tpAmazonShop = new TpAmazonShop().setId(tccFbaPlan.getShopId()).queryFirst();

                //获取制单人信息
                TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setStatus(1).queryFirst();
                String auditingUser = null;
                Date auditingTime = null;
                if (tsUserChange != null) {
                    auditingUser = tsUserChange.getUserId() + '/' + tsUserChange.getUserName();
                    auditingTime = new Date();
                } else {
                    return R.error("未查询到制单人信息！");
                }
                //整个计划单关联的发货单审核
                List<TccFbaDeliver> tccFbaDeliverList = new TccFbaDeliver().setFbaPlanBid(bid).queryList();

                for (TccFbaDeliver tccFbaDeliver1 : tccFbaDeliverList) {
                    if (tccFbaDeliver1.getStatus() != TccFbaDeliverEnum.Status.NOTRANSSHIPPED.value) {
                        return R.error("FBA发货单货件状态只允许待转运状态,请核实数据!");
                    }
                }

                List<TccFbaBoxUpInfo> tccFbaBoxUpInfoListOld = new TccFbaBoxUpInfo().setBidFbaPlan(tccFbaPlan.getBid()).queryList();

                //查询所有的发货单FBA信息
                List<TccFbaDeliverItem> tccFbaDeliverItemListOld = new TccFbaDeliverItem().setFbaPlanBid(tccFbaPlan.getBid()).queryList();

                List<TccLogisticsMethodItem> tdjzPrice;
                BigDecimal jfStart = BigDecimal.ZERO;
                BigDecimal jfEnd = BigDecimal.ZERO;
                BigDecimal jfFee = BigDecimal.ZERO;

                for (TccFbaDeliver tccFbaDeliver1 : tccFbaDeliverList) {
                    TccFbaLogisticsMethod tccFbaLogisticsMethod = new TccFbaLogisticsMethod().setSourceBid(tccFbaDeliver1.getBid()).setSourceType(TccFbaLogisticsMethodEnum.SourceType.FBAFH.value).queryFirst();

                    List<TccFbaDeliverItem> tccFbaDeliverItemList = tccFbaDeliverItemListOld.stream()
                            .filter(tccFbaDeliverItem -> tccFbaDeliverItem.getPbid().equals(tccFbaDeliver1.getBid()))
                            .collect(Collectors.toList());

                    //可发送的目的地
                    List<TccAdditionalBillingTwo> tccAdditionalBillingTwoList = new TccAdditionalBillingTwo().setMethodId(tccFbaLogisticsMethod.getLogsticsWayId()).queryList();

                    if (tccAdditionalBillingTwoList.size() != 0) {
                        Boolean isWarehouseCode = false;
                        for (TccFbaDeliverItem tccFbaDeliverItem : tccFbaDeliverItemList) {
                            for (TccFbaBoxUpInfo tccFbaBoxUpInfo : tccFbaBoxUpInfoListOld) {
                                if (tccFbaDeliverItem.getFbaBoxUpInfoId().equals(tccFbaBoxUpInfo.getId())) {
                                    for (TccAdditionalBillingTwo tccAdditionalBillingTwo : tccAdditionalBillingTwoList) {
                                        if (tccFbaBoxUpInfo.getFbaWarehouse().equals(tccAdditionalBillingTwo.getWarehouseCode())) {
                                            isWarehouseCode = true;
                                        }
                                    }
                                }
                            }

                        }
                        if (!isWarehouseCode) {
                            return R.error("选择的数据中物流服务对应的目的地仓库不符合可发选择,请核实后再操作!");
                        }
                    }

                    TccFbaFeeDetails tccFbaFeeDetailsNew = new TccFbaFeeDetails().setSourceType(TccFbaFeeDetailsEnum.SourceType.DELIVER.value).setSourceBid(tccFbaDeliver1.getBid()).queryFirst();

                    //计重梯度+抛重梯度
                    List<TccLogisticsMethodItem> tccLogisticsMethodItemList = new TccLogisticsMethodItem()
                            .setMethodId(tccFbaLogisticsMethod.getLogsticsWayId())
                            .queryList();
                    //计重梯度
                    List<TccLogisticsMethodItem> jzTdList = tccLogisticsMethodItemList.stream().filter(tccLogisticsMethodItem ->
                            TccLogisticsMethodItemEnum.LogisticsMethodType.JZTD.value.equals(tccLogisticsMethodItem.getLogisticsMethodType())).collect(Collectors.toList());

                    BigDecimal finalWeightCal = tccFbaFeeDetailsNew.getWeightCal();

                    tdjzPrice = jzTdList.stream().filter(tccLogisticsMethodItem -> finalWeightCal.compareTo(tccLogisticsMethodItem.getHeavySn()) >= 0
                            && finalWeightCal.compareTo(tccLogisticsMethodItem.getHeavyEn()) <= 0).collect(Collectors.toList());

                    //计重
                    if (tdjzPrice.size() == 0) {
                        return R.error("该货件不符合物流服务的发货重要要求，请进行物流服务调整!");
                    }
                }


                //库存解冻并出库(按照FBA计划单明细)
                List<TccFbaPlanItem> tccFbaPlanItemList = new TccFbaPlanItem().setBidFbaPlan(tccFbaPlan.getBid()).queryList();
                for (TccFbaPlanItem tccFbaPlanItem : tccFbaPlanItemList) {
                    //解冻流水
                    tccStockControlService.thaw(
                            tccFbaPlanItem.getStockControlId(),
                            tccFbaPlanItem.getNumPlanDeliver(),
                            TccStockFrozenRunningEnum.SourceType.TCC_DELIVER_FINISH.value,
                            tccFbaPlan.getBid(),
                            tccFbaPlan.getId());

                //出库
                String remark1 = "FBA计划单号：" + tccFbaPlan.getBid() + "出库FBA计划数量";
                //实际装箱数量
                Integer numOut = tccFbaPlanItem.getNumRealityBox();
                Integer source = TccStockSourceEnum.Source.TCC_FbaDeliver.value;
                R r = tccStockControlService.outWithRunning(tccFbaPlanItem.getStockControlId(), remark1, numOut, tccFbaPlan.getBid(), source, tccFbaPlan.getId());
                if (r.getCode() != 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error(r.getMsg());
                }
            }

                //查询所有发货单的箱子信息
                List<TccFbaDeliverSon> tccFbaDeliverSonListOld = new TccFbaDeliverSon().setFbaPlanBid(tccFbaPlan.getBid()).queryList();
                //查询箱子对应的实际商品数据
                List<TccFbaBoxDetail> tccFbaBoxDetailListOld = new TccFbaBoxDetail().setBidFbaPlan(tccFbaPlan.getBid()).queryList();
                //箱子商品信息
                List<TccFbaBoxUpItem> tccFbaBoxUpItemListOld = new TccFbaBoxUpItem().setBidFbaPlan(tccFbaPlan.getBid()).queryList();
                //资金解冻
                TccFbaFeeDetails tccFbaFeeDetails = new TccFbaFeeDetails().setSourceType(TccFbaFeeDetailsEnum.SourceType.PLAN.value).setSourceBid(tccFbaPlan.getBid()).queryFirst();
                if (tccFbaFeeDetails.getPriceTranPredict().compareTo(BigDecimal.ZERO) != 0) {
                    //解冻资金
                    tcwAccountCountForCompanyService.thaw(
                            tccFbaPlan.getVgsbm(),
                            tccFbaFeeDetails.getPriceTranPredict(),
                            TcwOperateFrozenRunningEnum.DocumentType.TCC_FbaPlan.value,
                            tccFbaFeeDetails.getId(),
                            tccFbaPlan.getBid(),
                            tccFbaPlan.getBid()
                    );
                }

                for (TccFbaDeliver tccFbaDeliver1 : tccFbaDeliverList) {
                    TccFbaFeeDetails tccFbaFeeDetailsNew = new TccFbaFeeDetails().setSourceType(TccFbaFeeDetailsEnum.SourceType.DELIVER.value).setSourceBid(tccFbaDeliver1.getBid()).queryFirst();
                    R r = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
                            tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(), "GS0899", "物流部（中间账户）",
                            "物流服务→头程运费", tccFbaFeeDetailsNew.getPriceTranPredict().negate(), tccFbaDeliver1.getCreateTime(), auditingTime,
                            "FBA计划单号:" + tccFbaPlan.getBid() + "，FBA发货单号:" + tccFbaDeliver1.getBid(),
                            tccFbaDeliver1.getBid(), auditingTime);
                    if (r.getCode() != 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return R.error(r.getMsg());
                    }

                    r = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
                            "GS0899", "物流部（中间账户）", tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(),
                            "物流服务→头程运费", tccFbaFeeDetailsNew.getPriceTranPredict(), tccFbaDeliver1.getCreateTime(), auditingTime,
                            "FBA计划单号:" + tccFbaPlan.getBid() + "，FBA发货单号:" + tccFbaDeliver1.getBid(),
                            tccFbaDeliver1.getBid(), auditingTime);
                    if (r.getCode() != 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return R.error(r.getMsg());
                    }

                    //箱子数量
                    Integer boxNum = 0;
                    BigDecimal boxNumPrice = BigDecimal.ZERO;
                    //透明标
                    Integer tagTransparentNum = 0;
                    BigDecimal tagTransparentPrice = BigDecimal.ZERO;
                    Map<String, Integer> transparentReMap = new HashMap<>();
                    String finaltagTransparentRe = "";
                    //欧代标
                    Integer tagEurNum = 0;
                    BigDecimal tagEurPrice = BigDecimal.ZERO;
                    Map<String, Integer> tagEurMap = new HashMap<>();
                    String finaltagEurRe = "";

                    //收取标签费用/箱子费用
                    List<TccFbaDeliverItem> tccFbaDeliverItemList = tccFbaDeliverItemListOld.stream()
                            .filter(tccFbaDeliverItem -> tccFbaDeliverItem.getPbid().equals(tccFbaDeliver1.getBid()))
                            .collect(Collectors.toList());
                    for (TccFbaDeliverItem tccFbaDeliverItem : tccFbaDeliverItemList) {
                        List<TccFbaDeliverSon> tccFbaDeliverSonList = tccFbaDeliverSonListOld.stream()
                                .filter(tccFbaDeliverSon -> tccFbaDeliverSon.getFbaDeliverItemId().equals(tccFbaDeliverItem.getId()))
                                .collect(Collectors.toList());
                        for (TccFbaDeliverSon tccFbaDeliverSon : tccFbaDeliverSonList) {
                            boxNum = boxNum + 1;
                            //查询箱子对应的实际商品数据
                            List<TccFbaBoxDetail> tccFbaBoxDetailList = tccFbaBoxDetailListOld.stream()
                                    .filter(tccFbaBoxDetail -> tccFbaBoxDetail.getBoxId().equals(tccFbaDeliverSon.getFbaBoxId()))
                                    .collect(Collectors.toList());
                            for (TccFbaBoxDetail tccFbaBoxDetail : tccFbaBoxDetailList) {
                                List<TccFbaBoxUpItem> tccFbaBoxUpItemList = tccFbaBoxUpItemListOld.stream()
                                        .filter(tccFbaBoxUpItem -> tccFbaBoxUpItem.getId().equals(tccFbaBoxDetail.getBoxUpItemId()))
                                        .collect(Collectors.toList());
                                TccFbaBoxUpItem tccFbaBoxUpItem = tccFbaBoxUpItemList.get(0);
                                List<TccFbaPlanItem> tccFbaPlanItemListNew = tccFbaPlanItemList.stream()
                                        .filter(tccFbaPlanItem -> tccFbaPlanItem.getId().equals(tccFbaBoxUpItem.getFbaPlanItemId()))
                                        .collect(Collectors.toList());
                                TccFbaPlanItem tccFbaPlanItem = tccFbaPlanItemListNew.get(0);
                                //透明标
                                if (tccFbaPlanItem.getIsSign().equals("是")) {
                                    if (transparentReMap.get(tccFbaPlanItem.getCommodityCode()) == null) {
                                        transparentReMap.put(tccFbaPlanItem.getCommodityCode(), tccFbaBoxDetail.getNum());
                                        tagTransparentNum = tagTransparentNum + tccFbaBoxDetail.getNum();
                                    } else {
                                        Integer transparentRe = transparentReMap.get(tccFbaPlanItem.getCommodityCode());
                                        tagTransparentNum = tagTransparentNum + tccFbaBoxDetail.getNum();
                                        transparentReMap.put(tccFbaPlanItem.getCommodityCode(), transparentRe);
                                    }
                                }
                                //判断店铺欧代标是否需要打印
                                if (tpAmazonShop.getEuStatus() == 1) {
                                    if (tagEurMap.get(tccFbaPlanItem.getCommodityCode()) == null) {
                                        tagEurMap.put(tccFbaPlanItem.getCommodityCode(), tccFbaBoxDetail.getNum());
                                        tagEurNum = tagEurNum + tccFbaBoxDetail.getNum();
                                    } else {
                                        Integer transparentRe = tagEurMap.get(tccFbaPlanItem.getCommodityCode());
                                        tagEurNum = tagEurNum + tccFbaBoxDetail.getNum();
                                        tagEurMap.put(tccFbaPlanItem.getCommodityCode(), transparentRe);
                                    }

                                }
                            }
                        }
                    }

                    //纸箱费
                    boxNumPrice = new BigDecimal(boxNum).multiply(new BigDecimal(15)).setScale(2, BigDecimal.ROUND_HALF_UP);

                    r = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
                            tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(), "GS0608", "仓储部",
                            "仓储服务→纸箱费", boxNumPrice.negate(), tccFbaDeliver1.getCreateTime(), auditingTime,
                            "FBA计划单号:" + tccFbaPlan.getBid() + "，FBA发货单号:" + tccFbaDeliver1.getBid() + ",箱子数量:" + boxNum + "个",
                            tccFbaDeliver1.getBid(), auditingTime);
                    if (r.getCode() != 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return R.error(r.getMsg());
                    }

                    r = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
                            "GS0608", "仓储部", tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(),
                            "仓储服务→纸箱费", boxNumPrice, tccFbaDeliver1.getCreateTime(), auditingTime,
                            "FBA计划单号:" + tccFbaPlan.getBid() + "，FBA发货单号:" + tccFbaDeliver1.getBid() + ",箱子数量:" + boxNum + "个",
                            tccFbaDeliver1.getBid(), auditingTime);
                    if (r.getCode() != 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return R.error(r.getMsg());
                    }

                    //透明计划贴标费
                    if (tagTransparentNum != 0) {

                        tagTransparentPrice = new BigDecimal(tagTransparentNum).multiply(new BigDecimal(0.6)).setScale(2, BigDecimal.ROUND_HALF_UP);

                        //备注
                        for (Map.Entry<String, Integer> entry : transparentReMap.entrySet()) {
                            finaltagTransparentRe = finaltagTransparentRe + "商品编码:" + entry.getKey() + ",数量:" + entry.getValue() + ",";
                        }

                        r = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
                                tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(), "GS0608", "仓储部",
                                "仓储服务→透明计划贴标费", tagTransparentPrice.negate(), tccFbaDeliver1.getCreateTime(), auditingTime,
                                "FBA计划单号:" + tccFbaPlan.getBid() + "，FBA发货单号:" + tccFbaDeliver1.getBid() + "," + "透明标:" + tagTransparentNum + "个",
                                tccFbaDeliver1.getBid(), auditingTime);
                        if (r.getCode() != 0) {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return R.error(r.getMsg());
                        }

                        r = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
                                "GS0608", "仓储部", tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(),
                                "仓储服务→透明计划贴标费", tagTransparentPrice, tccFbaDeliver1.getCreateTime(), auditingTime,
                                "FBA计划单号:" + tccFbaPlan.getBid() + "，FBA发货单号:" + tccFbaDeliver1.getBid() + "," + "透明标:" + tagTransparentNum + "个",
                                tccFbaDeliver1.getBid(), auditingTime);
                        if (r.getCode() != 0) {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return R.error(r.getMsg());
                        }
                    }

                    //欧代标费用
                    if (tagEurNum != 0) {

                        tagEurPrice = new BigDecimal(tagEurNum).multiply(new BigDecimal(0.6)).setScale(2, BigDecimal.ROUND_HALF_UP);

                        //备注
                        for (Map.Entry<String, Integer> entry : tagEurMap.entrySet()) {
                            finaltagEurRe = finaltagEurRe + "商品编码:" + entry.getKey() + ",数量:" + entry.getValue() + ",";
                        }

                        r = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
                                tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(), "GS0608", "仓储部",
                                "仓储服务→欧代贴标费", tagEurPrice.negate(), tccFbaDeliver1.getCreateTime(), auditingTime,
                                "FBA计划单号:" + tccFbaPlan.getBid() + "，FBA发货单号:" + tccFbaDeliver1.getBid() + "," + "欧代标:" + tagEurNum,
                                tccFbaDeliver1.getBid(), auditingTime);
                        if (r.getCode() != 0) {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return R.error(r.getMsg());
                        }

                        r = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
                                "GS0608", "仓储部", tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(),
                                "仓储服务→欧代贴标费", tagEurPrice, tccFbaDeliver1.getCreateTime(), auditingTime,
                                "FBA计划单号:" + tccFbaPlan.getBid() + "，FBA发货单号:" + tccFbaDeliver1.getBid() + "," + "欧代标:" + tagEurNum,
                                tccFbaDeliver1.getBid(), auditingTime);
                        if (r.getCode() != 0) {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return R.error(r.getMsg());
                        }
                    }


                    tccFbaDeliver1.setStatus(TccFbaDeliverEnum.Status.TRANSSHIPPED.value);
                    tccFbaDeliver1.setAuditingTime(auditingTime);
                    tccFbaDeliver1.setAuditingUser(auditingUser);
                    tccFbaDeliver1.setTransparentNum(tagTransparentNum);
                    tccFbaDeliver1.setEurNum(tagEurNum);
                    tccFbaDeliver1.setBoxNum(boxNum);
                    tccFbaDeliverMapper.update(tccFbaDeliver1);
                }
            }
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(e.getCause().getMessage());
        }
        return R.ok("转运审核成功!");
    }

    /**
     * 新增FBA发货单（调用一次新增一个发货单，以及对应子列表信息）
     * @param tccFbaDeliverAdd 发货单信息集
     * @return 新增结果
     *
     */

    @Override
    public R addFbaDeliver(TccFbaDeliverAdd tccFbaDeliverAdd) throws Exception {
        //获取单号信息
        String bid = commonApiService.getCommonNextBid(MenuId.TCC_FbaDeliverX);
        logger.info("新增FBA发货单传参：bid="+bid+"；tccFbaDeliverAdd="+tccFbaDeliverAdd);

        TccFbaDeliver tccFbaDeliver = new TccFbaDeliver();
        tccFbaDeliver.setBid(bid);
        tccFbaDeliver.setFbaPlanBid(tccFbaDeliverAdd.getTccFbaPlan().getBid());
        tccFbaDeliver.setStatus(TccFbaDeliverEnum.Status.NOTRANSSHIPPED.value);
        tccFbaDeliverMapper.insert(tccFbaDeliver);

        for (TccFbaDeliverItemAdd tccFbaDeliverItemAdd : tccFbaDeliverAdd.getTccFbaDeliverItemAddList()){
            TccFbaDeliverItem tccFbaDeliveItem = new TccFbaDeliverItem();
            tccFbaDeliveItem.setPbid(bid);
            tccFbaDeliveItem.setFbaBoxUpInfoId(tccFbaDeliverItemAdd.getFbaBoxUpInfoId());
            tccFbaDeliveItem.setDeliveryWindowOptionId(tccFbaDeliverItemAdd.getDeliveryWindowOptionId());
            tccFbaDeliveItem.setTransportationOptionId(tccFbaDeliverItemAdd.getTransportationOptionId());
            tccFbaDeliveItem.setFbaPlanBid(tccFbaDeliver.getFbaPlanBid());
            tccFbaDeliveItem.setFbaBoxUpBid(tccFbaDeliverItemAdd.getFbaBoxUpBid());
            tccFbaDeliveItem.setStatus(1);
            tccFbaDeliveItem.setApiTrackStatus(TccFbaDeliverEnum.ApiTrackStatus.NO.value);
            tccFbaDeliverItemMapper.insert(tccFbaDeliveItem);

            for (TccFbaDeliverSonAdd tccFbaDeliverSonAdd : tccFbaDeliverItemAdd.getTccFbaDeliverSonAddList()){
                TccFbaDeliverSon tccFbaDeliverSon = new TccFbaDeliverSon();
                tccFbaDeliverSon.setPbid(bid);
                tccFbaDeliverSon.setFbaDeliverItemId(tccFbaDeliveItem.getId());
                tccFbaDeliverSon.setFbaBoxId(tccFbaDeliverSonAdd.getTccFbaBox().getId());
                tccFbaDeliverSon.setBoxNo(tccFbaDeliverSonAdd.getBoxNo());
                tccFbaDeliverSon.setFbaPlanBid(tccFbaDeliverAdd.getTccFbaPlan().getBid());
                tccFbaDeliverSon.setFbaBoxUpBid(tccFbaDeliverSonAdd.getTccFbaBox().getBidBoxUp());
                tccFbaDeliverSon.setStatus(1);
                tccFbaDeliverSonMapper.insert(tccFbaDeliverSon);
            }
        }

        //计算逻辑
        computationalLogic(tccFbaDeliver,tccFbaDeliverAdd,1,null);
//        int i = 1/0;
        return R.ok("新增FBA发货单成功!");
    }

    /**
     * 计算逻辑
     * @param tccFbaDeliver
     * @return
     */
    private R computationalLogic(TccFbaDeliver tccFbaDeliver,TccFbaDeliverAdd tccFbaDeliverAdd,Integer type,Integer isType
                                  ){
        if (type == 1){
            //生成过的不需要再生成
            Integer count = new TccFbaLogisticsMethod().setSourceType(1).setSourceBid(tccFbaDeliver.getBid()).count();
            if (count != 0){
                return R.ok("已存在不需要生成!");
            }
        }
        TccFbaPlan tccFbaPlan = tccFbaDeliverAdd.getTccFbaPlan();

        TccLogisticsMethod tccLogisticsMethod = tccFbaDeliverAdd.getTccLogisticsMethod();

        if (tccLogisticsMethod.getCoefficientWeight() == 0) {
            tccLogisticsMethod.setCoefficientWeight(5000);
        } else {
            tccLogisticsMethod.setCoefficientWeight(6000);
        }

        //运输类型维护
        TccTransportationType tccTransportationType = new TccTransportationType()
                .addLeftJoin("TCC_TransportationTypeItem B ON B.TransportationTypeId = A.id")
                .where("B.TransportationTypeZbCn = " + tccLogisticsMethod.getTransportationId())
                .queryFirst();
        //自动 - 按SUK发货 自动选择FREIGHT_LTL 发货
        if (tccFbaPlan.getCreationMethod() == 1 && tccFbaPlan.getDeliverState() == 1) {
            tccTransportationType = new TccTransportationType()
                    .setTransportationTypeEn("FREIGHT_LTL").queryFirst();
        }
        //查询仓库信息
        TccWarehouse tccWarehouse = new TccWarehouse().setCck(tccLogisticsMethod.getCck()).queryFirst();

        //计重梯度+抛重梯度
        List<TccLogisticsMethodItem> tccLogisticsMethodItemList = new TccLogisticsMethodItem()
                .setMethodId(tccLogisticsMethod.getId())
                .queryList();
        //计重梯度
        List<TccLogisticsMethodItem> jzTdList = tccLogisticsMethodItemList.stream().filter(tccLogisticsMethodItem ->
                TccLogisticsMethodItemEnum.LogisticsMethodType.JZTD.value.equals(tccLogisticsMethodItem.getLogisticsMethodType())).collect(Collectors.toList());
        //抛重梯度
        List<TccLogisticsMethodItem> pzTdList = tccLogisticsMethodItemList.stream().filter(tccLogisticsMethodItem ->
                TccLogisticsMethodItemEnum.LogisticsMethodType.PZTD.value.equals(tccLogisticsMethodItem.getLogisticsMethodType())).collect(Collectors.toList());
        //材质梯度
        List<TccLogisticsMethodItemSon> czTdList = new TccLogisticsMethodItemSon()
                .setMethodId(tccLogisticsMethod.getId())
                .queryList();
        //目的地
        List<TccAdditionalBilling> tccAdditionalBillingList = new TccAdditionalBilling().setMethodId(tccLogisticsMethod.getId()).queryList();

        if (type == 2) {
            //可发送的目的地
            List<TccAdditionalBillingTwo> tccAdditionalBillingTwoList = new TccAdditionalBillingTwo().setMethodId(tccLogisticsMethod.getId()).queryList();

            if (tccAdditionalBillingTwoList.size() != 0) {
                Boolean isWarehouseCode = false;
                for (TccAdditionalBillingTwo tccAdditionalBillingTwo : tccAdditionalBillingTwoList) {
                    if (tccFbaDeliverAdd.getFbaWarehouse().equals(tccAdditionalBillingTwo.getWarehouseCode())) {
                        isWarehouseCode = true;
                    }
                }
                if (!isWarehouseCode) {
                    return R.error("选择的物流服务中目的地仓库不符合可发选择,请核实后再操作!");
                }
            }
        }

        //运输类型快递以外都是物流 0.快递|1.物流
        Integer transportation = 0;
        if (tccLogisticsMethod.getTransportationId() != 0) {
            transportation = 1;
        }

        //实重（kg）
        BigDecimal weightReal = BigDecimal.ZERO;
        //抛重（kg）
        BigDecimal weightVol = BigDecimal.ZERO;
        //计重（kg）
        BigDecimal weightCal = BigDecimal.ZERO;

        for (TccFbaDeliverItemAdd tccFbaDeliverItemAdd : tccFbaDeliverAdd.getTccFbaDeliverItemAddList()){
            for (TccFbaDeliverSonAdd tccFbaDeliverSonAdd : tccFbaDeliverItemAdd.getTccFbaDeliverSonAddList()){
                //获取每一个箱子数据获取
                TccFbaBox tccFbaBox = tccFbaDeliverSonAdd.getTccFbaBox();
                //0.快递|1.物流
                if (transportation == 0) {
                    //实重（kg）=FBA装箱单号--MAX（箱规重量+约分规则，单箱起重（kg））--之和
                    weightReal = weightReal.add(
                            ruleReduction(tccLogisticsMethod, tccFbaBox.getBoxWeight())
                                    .max(tccLogisticsMethod.getWeightCalBySingle())
                    );
                    //抛重（kg）=FBA装箱单号-（箱规尺寸相乘/抛货系数）+约分规则，--之和
                    weightVol = weightVol.add(ruleReduction(tccLogisticsMethod, (tccFbaBox.getBoxLong().multiply(tccFbaBox.getBoxWide()).multiply(tccFbaBox.getBoxHigh()))
                            .divide(new BigDecimal(tccLogisticsMethod.getCoefficientWeight()), 2, RoundingMode.HALF_UP)));
                } else {
                    //实重（kg）=FBA装箱单号--MAX（箱规重量，单箱起重（kg））--之和
                    weightReal = weightReal.add(
                            tccFbaBox.getBoxWeight()).max(tccLogisticsMethod.getWeightCalBySingle()
                    );
                    //抛重（kg）=FBA装箱单号-（箱规尺寸相乘/抛货系数）--之和
                    weightVol = weightVol.add((tccFbaBox.getBoxLong().multiply(tccFbaBox.getBoxWide()).multiply(tccFbaBox.getBoxHigh()))
                            .divide(new BigDecimal(tccLogisticsMethod.getCoefficientWeight()), 2, RoundingMode.HALF_UP));
                }
            }
        }


        //0.快递|1.物流
        if (transportation == 0) {
            //清关方式（0自税、1包税）
            if (tccLogisticsMethod.getNameLogsticsClearance() == TccFbaLogisticsMethodEnum.NameLogsticsClearance.FARMINGTAXES.value) {
                //计重（kg）=MAX【实重，单票起重（kg）】  20250409取消这个判断
//                weightCal = weightReal.max(tccLogisticsMethod.getSinglePassCrane());
            } else {
                //计重（kg）=MAX【MAX（实重,抛重），单票起重（kg）】
                weightCal = weightReal.max(weightVol);
                weightCal = weightCal.max(tccLogisticsMethod.getSinglePassCrane());
            }
        } else {
            if (tccLogisticsMethod.getNameLogsticsClearance() == TccFbaLogisticsMethodEnum.NameLogsticsClearance.FARMINGTAXES.value) {
                //计重（kg）=MAX【实重+约分规则，单票起重（kg）】 . 20250409取消这个判断 只留约分规则
                weightCal = ruleReduction(tccLogisticsMethod, weightReal);
//                weightCal = weightCal.max(tccLogisticsMethod.getSinglePassCrane());
            } else {
                //计重（kg）=MAX【MAX（实重,抛重）+约分规则，单票起重（kg）】
                weightCal = weightReal.max(weightVol);
                weightCal = ruleReduction(tccLogisticsMethod, weightCal);
                weightCal = weightCal.max(tccLogisticsMethod.getSinglePassCrane());
            }
        }

        //品名数量
        Set<String> gradeNum = new HashSet<>();
        //材质费用
        BigDecimal czFee = BigDecimal.ZERO;
        String czCn = "";
        String czEn = "";
        List<TccLogisticsMethodItem> tdjzPrice;

        List<TccLogisticsMethodItem> tdPzPrice;

        List<TccAdditionalBilling> tccAdditionalBillingListNew;

        //计重梯度
        BigDecimal jfStart = BigDecimal.ZERO;
        BigDecimal jfEnd = BigDecimal.ZERO;
        BigDecimal jfFee = BigDecimal.ZERO;

        //抛重梯度
        BigDecimal pzStart = BigDecimal.ZERO;
        BigDecimal pzEnd = BigDecimal.ZERO;
        BigDecimal pzFee = BigDecimal.ZERO;

        //目的地附加费
        BigDecimal additionalBilling = BigDecimal.ZERO;
        String warehouseArea = "空";
        String firstPostalCode = "空";
        String warehouseCode = "空";

        for (TccFbaPlanItem tccFbaPlanItem : tccFbaDeliverAdd.getTccFbaPlanItemList()) {
            //不一样的品名数=(商品中文、海关编码、材质中文只要一个不同)
            String join = tccFbaPlanItem.getNameGoodsCn() + '-' + tccFbaPlanItem.getCodeGoodsHs() + '-' + tccFbaPlanItem.getNameMaterialCn();
            gradeNum.add(join);

            //判断是否是混合材质
            if (tccFbaPlanItem.getNameMaterialCn().indexOf(",") == -1) {
                //赋值材质附加费(取最大值)
                for (int j = 0; j < czTdList.size(); j++) {
                    if (czTdList.get(j).getMaterialNameCn().equals(tccFbaPlanItem.getNameMaterialCn())) {
                        if (czTdList.get(j).getAdditionalMaterialBilling().compareTo(czFee) > 0) {
                            czFee = (czTdList.get(j).getAdditionalMaterialBilling());
                            czCn = (czTdList.get(j).getMaterialNameCn());
                            czEn = (czTdList.get(j).getMaterialNameEn());
                        }
                    }
                }
            } else {
                String[] nameMaterialCnList = tccFbaPlanItem.getNameMaterialCn().split(",");
                for (String nameMaterialCn : nameMaterialCnList) {
                    for (int j = 0; j < czTdList.size(); j++) {
                        if (czTdList.get(j).getMaterialNameCn().equals(nameMaterialCn)) {
                            if (czTdList.get(j).getAdditionalMaterialBilling().compareTo(czFee) > 0) {
                                czFee = (czTdList.get(j).getAdditionalMaterialBilling());
                                czCn = (czTdList.get(j).getMaterialNameCn());
                                czEn = (czTdList.get(j).getMaterialNameEn());
                            }
                        }
                    }
                }
            }
        }

        //计重梯度价（￥/kg） 参照“计重”对应范围的梯度价
        BigDecimal finalWeightCal = weightCal;
        tdjzPrice = jzTdList.stream().filter(tccLogisticsMethodItem -> finalWeightCal.compareTo(tccLogisticsMethodItem.getHeavySn()) >= 0
                && finalWeightCal.compareTo(tccLogisticsMethodItem.getHeavyEn()) <= 0).collect(Collectors.toList());

        //计重
        if (tdjzPrice.size() != 0) {
            jfStart = tdjzPrice.get(0).getHeavySn();
            jfEnd = tdjzPrice.get(0).getHeavyEn();
            jfFee = tdjzPrice.get(0).getPrice();
        }else {
            if (type == 2) {
                //当不存在梯度区间,判断最近的大值,反之判断不存在区间不允许通过
                tdjzPrice = jzTdList.stream().filter(tccLogisticsMethodItem -> finalWeightCal.compareTo(tccLogisticsMethodItem.getHeavySn()) < 0
                ).sorted(Comparator.comparing(TccLogisticsMethodItem::getHeavySn)).collect(Collectors.toList());
                if (tdjzPrice.size() != 0){
                    if (isType != null){
                        weightCal = tdjzPrice.get(0).getHeavySn();
                        jfStart = tdjzPrice.get(0).getHeavySn();
                        jfEnd = tdjzPrice.get(0).getHeavyEn();
                        jfFee = tdjzPrice.get(0).getPrice();
                    }else {
                        return R.ok("该货件不满足物流服务最小发货重量，请确认是否按照最小发货:"+ tdjzPrice.get(0).getHeavySn() +"(kg)发货");
                    }
                }else {
                    return R.error("该货件不符合物流服务的发货重要要求，请进行物流服务调整!");
                }
            }
        }

        //抛重附加费（￥/kg）---自税为0，包税取值
        if (tccLogisticsMethod.getNameLogsticsClearance() == TccFbaLogisticsMethodEnum.NameLogsticsClearance.FARMINGTAXES.value) {
            //抛重附加费（￥/kg） 参照“抛重-实重”对应范围的梯度价
            BigDecimal finalWeightVol = weightVol.subtract(weightReal);
            tdPzPrice = pzTdList.stream().filter(tccLogisticsMethodItem -> finalWeightVol.compareTo(tccLogisticsMethodItem.getHeavySn()) >= 0
                    && finalWeightVol.compareTo(tccLogisticsMethodItem.getHeavyEn()) <= 0).collect(Collectors.toList());
            //抛重
            if (tdPzPrice.size() != 0) {
                pzStart = tdPzPrice.get(0).getHeavySn();
                pzEnd = tdPzPrice.get(0).getHeavyEn();
                pzFee = tdPzPrice.get(0).getPrice();
            }
        }

        //目的地附加计费（￥/kg）】
        if (tccAdditionalBillingList.size() != 0) {
            String finalWarehouse = tccFbaDeliverAdd.getFbaWarehouse();
            tccAdditionalBillingListNew = tccAdditionalBillingList.stream().filter(tccAdditionalBilling -> finalWarehouse.equals(tccAdditionalBilling.getWarehouseCode())
            ).collect(Collectors.toList());
            //目的地 仓库代码满足直接取 反之 取邮编首数字开头的比并且仓库为空
            if (tccAdditionalBillingListNew.size() != 0) {
                additionalBilling = tccAdditionalBillingListNew.get(0).getAdditionalBilling();
                warehouseArea = tccAdditionalBillingListNew.get(0).getWarehouseArea();
                firstPostalCode = tccAdditionalBillingListNew.get(0).getFirstPostalCode();
                warehouseCode = tccAdditionalBillingListNew.get(0).getWarehouseCode();
            } else {
                String finalWarehouseAddr = tccFbaDeliverAdd.getFbaWarehouseAddr();
                tccAdditionalBillingListNew = tccAdditionalBillingList.stream().filter(tccAdditionalBilling ->
                        (tccAdditionalBilling.getWarehouseCode() == null || tccAdditionalBilling.getWarehouseCode().equals("")) && tccAdditionalBilling.getFirstPostalCode()!=null && finalWarehouseAddr.startsWith(tccAdditionalBilling.getFirstPostalCode())

                ).collect(Collectors.toList());
                if (tccAdditionalBillingListNew.size() != 0) {
                    additionalBilling = tccAdditionalBillingListNew.get(0).getAdditionalBilling();
                    warehouseArea = tccAdditionalBillingListNew.get(0).getWarehouseArea();
                    firstPostalCode = tccAdditionalBillingListNew.get(0).getFirstPostalCode();
                    warehouseCode = tccAdditionalBillingListNew.get(0).getWarehouseCode();
                }
            }
        }

        //清关服务费(￥)---包税为0，自税取值
        if (tccLogisticsMethod.getNameLogsticsClearance() == TccFbaLogisticsMethodEnum.NameLogsticsClearance.FARMINGTAXES.value) {
            tccLogisticsMethod.setClearanceOpeAmount(BigDecimal.ZERO);
        }

        Double freeProNameNumSj = 0.0;
        //品名判断数值
        Boolean numWeightCal = true;

        //免费品名数量  自税=免费品名数量  包税 (免费品名数量/2，向下取整  免费品名数量/2，向上取整 免费品名数量)
        if (tccLogisticsMethod.getNameLogsticsClearance() == TccFbaLogisticsMethodEnum.NameLogsticsClearance.FARMINGTAXES.value) {
            //1.实际计重<单票起重的二分之一,实际品名数=免费品名数/2&向下取整
            numWeightCal = weightCal.compareTo(tccLogisticsMethod.getSinglePassCrane().divide(new BigDecimal(2))) < 0;
            if (numWeightCal) {
                freeProNameNumSj = Math.floor(Double.valueOf(tccLogisticsMethod.getFreeProNameNum()) / 2.0);
            }
            //2.实际计重>=单票起重的二分之一,实际品名数=免费品名数/2&向上取整
            if (!numWeightCal && weightCal.compareTo(tccLogisticsMethod.getSinglePassCrane()) < 0) {
                freeProNameNumSj = Math.ceil(Double.valueOf(tccLogisticsMethod.getFreeProNameNum()) / 2.0);
            }
            if (weightCal.compareTo(tccLogisticsMethod.getSinglePassCrane()) >= 0) {
                //3.实际计重>=单票起重,实际品名数=免费品名数
                freeProNameNumSj = tccLogisticsMethod.getSinglePassCrane().doubleValue();
            }
        } else {
            freeProNameNumSj = tccLogisticsMethod.getFreeProNameNum().doubleValue();
        }

        if (type == 2){
            //删除
            storageMapper.deleteFbaLogisticsMethodBySourceTypeAndSourceBid(TccFbaLogisticsMethodEnum.SourceType.FBAFH.value,tccFbaDeliver.getBid());
            storageMapper.deleteFbaFeeDetailsBySourceTypeAndSourceBid(TccFbaFeeDetailsEnum.SourceType.DELIVER.value,tccFbaDeliver.getBid());
        }
        //新增FBA物流维护
        TccFbaLogisticsMethod tccFbaLogisticsMethod = new TccFbaLogisticsMethod();
        BeanUtils.copyProperties(tccLogisticsMethod, tccFbaLogisticsMethod);
        tccFbaLogisticsMethod.setId(null);
        tccFbaLogisticsMethod.setLogsticsWayId(tccLogisticsMethod.getId());
        tccFbaLogisticsMethod.setSourceType(TccFbaLogisticsMethodEnum.SourceType.FBAFH.value);
        tccFbaLogisticsMethod.setSourceBid(tccFbaDeliver.getBid());
        tccFbaLogisticsMethod.setTransportationCn(tccTransportationType.getTransportationTypeCn());
        tccFbaLogisticsMethod.setTransportationEn(tccTransportationType.getTransportationTypeEn());
        tccFbaLogisticsMethod.setVck(tccWarehouse.getVck());
        //计重
        tccFbaLogisticsMethod.setJfStart(jfStart);
        tccFbaLogisticsMethod.setJfEnd(jfEnd);
        tccFbaLogisticsMethod.setJfFee(jfFee);

        //抛重
        tccFbaLogisticsMethod.setPzStart(pzStart);
        tccFbaLogisticsMethod.setPzEnd(pzEnd);
        tccFbaLogisticsMethod.setPzFee(pzFee);

        //材质
        tccFbaLogisticsMethod.setCzFee(czFee);
        tccFbaLogisticsMethod.setCzCn(czCn);
        tccFbaLogisticsMethod.setCzEn(czEn);
        //目的地
        tccFbaLogisticsMethod.setWarehouseArea(warehouseArea);
        tccFbaLogisticsMethod.setFirstPostalCode(firstPostalCode);
        tccFbaLogisticsMethod.setWarehouseCode(warehouseCode);
        tccFbaLogisticsMethod.setAdditionalBilling(additionalBilling.toString());

        //实际品名数量
        tccFbaLogisticsMethod.setFreeProNameNumSj(freeProNameNumSj.intValue());
        tccFbaLogisticsMethodMapper.insert(tccFbaLogisticsMethod);

        TccFbaFeeDetails tccFbaFeeDetails = new TccFbaFeeDetails();
        tccFbaFeeDetails.setWeightReal(weightReal);
        tccFbaFeeDetails.setWeightVol(weightVol);
        tccFbaFeeDetails.setWeightCal(weightCal);
        //实际计重费（￥）=计重（kg）*【计重梯度价（￥/kg）+抛重附加费（￥/kg）+目的地附加计费（￥/kg）】
        tccFbaFeeDetails.setPriceTranCalWeight((tccFbaLogisticsMethod.getJfFee().add(tccFbaLogisticsMethod.getPzFee()).add(additionalBilling)
        ).multiply(weightCal).setScale(2, BigDecimal.ROUND_HALF_UP));
        tccFbaFeeDetails.setNumProName(gradeNum.size());
        //（实际品名附加费（￥）=MAX【（品名数量-实际免费品名数量）,0】*品名附加计费标准（￥/个）
        Integer exceedNum = gradeNum.size() - tccFbaLogisticsMethod.getFreeProNameNumSj();
        tccFbaFeeDetails.setPriceProNameExtraPredict(exceedNum > 0 ?
                (new BigDecimal(exceedNum).multiply(tccFbaLogisticsMethod.getAdditionalStandardAmount())).setScale(2, BigDecimal.ROUND_HALF_UP)
                : BigDecimal.ZERO);
        tccFbaFeeDetails.setPriceQualityExtra(czCn);
        //实际材质附加费（￥）=计重（kg）*材质附加计费（￥/kg）
        tccFbaFeeDetails.setPriceQualityExtraPredict((czFee.multiply(weightCal)).setScale(2, BigDecimal.ROUND_HALF_UP));
        //实际附加费（￥）=实际品名附加费（￥）+实际材质附加费（￥）
        tccFbaFeeDetails.setPriceExtraPredict(tccFbaFeeDetails.getPriceProNameExtraPredict().add(
                tccFbaFeeDetails.getPriceQualityExtraPredict()));
        tccFbaFeeDetails.setSourceType(TccFbaFeeDetailsEnum.SourceType.DELIVER.value);
        tccFbaFeeDetails.setSourceBid(tccFbaDeliver.getBid());
        //实际物流费（总）=实际计重费（￥）+实际附加费（￥）+清关服务费(￥)
        tccFbaFeeDetails.setPriceTranPredict(tccFbaFeeDetails.getPriceTranCalWeight().add(tccFbaFeeDetails.getPriceExtraPredict()).add(tccFbaLogisticsMethod.getClearanceOpeAmount()));
        tccFbaFeeDetails.setStatus(1);
        tccFbaFeeDetails.setVgsbm(tccFbaPlan.getVgsbm());
        tccFbaFeeDetailsMapper.insert(tccFbaFeeDetails);
        return R.ok();
    }

    private BigDecimal ruleReduction(TccLogisticsMethod tccLogisticsMethod,BigDecimal amount){
        //约分规则
        if (tccLogisticsMethod.getDivisionalRule() == TccLogisticsMethodEnum.DivisionalRule.INTO1.value){
            amount = new BigDecimal(Math.ceil(amount.doubleValue()));
        }else if (tccLogisticsMethod.getDivisionalRule() == TccLogisticsMethodEnum.DivisionalRule.INTO_05_1.value){
            amount = FbaUtils.precision(amount);
        }
        return amount;
    }

    /*
     * 修改物流服务id（TCC_LogisticsMethod）
     * @param bid 发货单号
     * @param logisticsMethodId 物流服务id（TCC_LogisticsMethod）
     */
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
     @Override
     public R editLogisticsMethodId(String bid,long logisticsMethodId,Integer isType,Integer isTypeWc) throws Exception {
         logger.info(ShiroUtils.getUserId() + "修改物流服务id:bid=" + bid + "，logisticsMethodId=" + logisticsMethodId + "类型:" +isTypeWc);

         //发货单
         TccFbaDeliver tccFbaDeliver = new TccFbaDeliver().setBid(bid).queryFirst();
         if (isTypeWc == 0){
             if (tccFbaDeliver.getStatus() != TccFbaDeliverEnum.Status.NOTRANSSHIPPED.value){
                 return R.error("FBA发货单货件状态只允许待转运变更物流服务,请核实数据!");
             }
         }else {
             if (tccFbaDeliver.getStatus() != TccFbaDeliverEnum.Status.TRANSSHIPPED.value){
                 return R.error("FBA发货单货件状态只允许已转运变更物流服务,请核实数据!");
             }
         }


         //物流服务
         TccLogisticsMethod tccLogisticsMethod = new TccLogisticsMethod().setId(logisticsMethodId).queryFirst();

         //计划单
         TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(tccFbaDeliver.getFbaPlanBid()).queryFirst();

         //计划单子件详情
         List<TccFbaPlanItem> tccFbaPlanItemListNew = new TccFbaPlanItem().setBidFbaPlan(tccFbaPlan.getBid()).queryList();

         //旧得装箱箱子信息
         List<TccFbaBox> tccFbaBoxListOld = new TccFbaBox().setBidFbaPlan(tccFbaPlan.getBid()).queryList();

         //旧的箱子与商品之间的关联
         List<TccFbaBoxDetail> tccFbaBoxDetailListOld = new TccFbaBoxDetail().setBidFbaPlan(tccFbaPlan.getBid()).queryList();

         List<TccFbaDeliverItem> tccFbaDeliverItemList = new TccFbaDeliverItem().setPbid(bid).queryList();
         List<TccFbaDeliverItemAdd> tccFbaDeliverItemAddList = new ArrayList<>();
         String fbaWarehouseAddr = "";
         String fbaWarehouse = "";
         List<TccFbaPlanItem> tccFbaPlanItemList = new ArrayList<>();
         for (TccFbaDeliverItem tccFbaDeliverItem : tccFbaDeliverItemList) {
             TccFbaDeliverItemAdd tccFbaDeliverItemAdd = new TccFbaDeliverItemAdd();

             //FBA信息
             if (fbaWarehouseAddr.equals("")){
                 TccFbaBoxUpInfo tccFbaBoxUpInfo = new TccFbaBoxUpInfo().setId(tccFbaDeliverItem.getFbaBoxUpInfoId()).queryFirst();
                 fbaWarehouseAddr = tccFbaBoxUpInfo.getFbaWarehouseAddr();
                 fbaWarehouse = tccFbaBoxUpInfo.getFbaWarehouse();
             }
             //箱子信息
             List<TccFbaDeliverSon> tccFbaDeliverSonList = new TccFbaDeliverSon().setFbaDeliverItemId(tccFbaDeliverItem.getId()).queryList();
             List<TccFbaDeliverSonAdd> tccFbaDeliverSonAddList = new ArrayList<>();
             for (TccFbaDeliverSon tccFbaDeliverSon : tccFbaDeliverSonList){
                 TccFbaDeliverSonAdd tccFbaDeliverSonAdd = new TccFbaDeliverSonAdd();
                 tccFbaDeliverSonAdd.setBoxNo(tccFbaDeliverSon.getBoxNo());
                 //箱子数据
                 List<TccFbaBox> tccFbaBoxList = tccFbaBoxListOld.stream().filter(e -> e.getId().equals(tccFbaDeliverSon.getFbaBoxId())).collect(Collectors.toList());
                 if (tccFbaBoxList.size() != 0){
                     tccFbaDeliverSonAdd.setTccFbaBox(tccFbaBoxList.get(0));
                 }
                 tccFbaDeliverSonAddList.add(tccFbaDeliverSonAdd);

                 List<TccFbaBoxDetail> tccFbaBoxDetailList = tccFbaBoxDetailListOld.stream().filter(e -> e.getBoxId().equals(tccFbaDeliverSon.getFbaBoxId())).collect(Collectors.toList());
                 if (tccFbaBoxDetailList.size() != 0) {
                     for (TccFbaBoxDetail tccFbaBoxDetail : tccFbaBoxDetailList) {
                         TccFbaBoxUpItem tccFbaBoxUpItem = new TccFbaBoxUpItem().setId(tccFbaBoxDetail.getBoxUpItemId()).queryFirst();
                         //筛选有没有重复
                         List<TccFbaPlanItem> tccFbaPlanItemList1 = tccFbaPlanItemList.stream().filter(e -> e.getId().equals(tccFbaBoxUpItem.getFbaPlanItemId())).collect(Collectors.toList());
                         if (tccFbaPlanItemList1.size() == 0) {
                             tccFbaPlanItemList1 = tccFbaPlanItemListNew.stream().filter(e -> e.getId().equals(tccFbaBoxUpItem.getFbaPlanItemId())).collect(Collectors.toList());
                             if (tccFbaPlanItemList1.size() != 0) {
                                 tccFbaPlanItemList.add(tccFbaPlanItemList1.get(0));

                             }
                         }
                     }
                 }
             }

             tccFbaDeliverItemAdd.setTccFbaDeliverSonAddList(tccFbaDeliverSonAddList);
             tccFbaDeliverItemAdd.setFbaBoxUpInfoId(tccFbaDeliverItem.getFbaBoxUpInfoId());
             tccFbaDeliverItemAdd.setDeliveryWindowOptionId(tccFbaDeliverItem.getDeliveryWindowOptionId());
             tccFbaDeliverItemAdd.setTransportationOptionId(tccFbaDeliverItem.getTransportationOptionId());
             tccFbaDeliverItemAdd.setFbaBoxUpBid(tccFbaDeliverItem.getFbaBoxUpBid());
             tccFbaDeliverItemAddList.add(tccFbaDeliverItemAdd);
         }

         TccFbaDeliverAdd tccFbaDeliverAdd = new TccFbaDeliverAdd();
         tccFbaDeliverAdd.setTccFbaDeliverItemAddList(tccFbaDeliverItemAddList);
         tccFbaDeliverAdd.setTccLogisticsMethod(tccLogisticsMethod);
         tccFbaDeliverAdd.setTccFbaPlan(tccFbaPlan);
         tccFbaDeliverAdd.setTccFbaPlanItemList(tccFbaPlanItemList);
         tccFbaDeliverAdd.setFbaWarehouseAddr(fbaWarehouseAddr);
         tccFbaDeliverAdd.setFbaWarehouse(fbaWarehouse);


         R r = computationalLogic(tccFbaDeliver, tccFbaDeliverAdd,2, isType);
         if(r.getCode() == 1){
             TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
             return r;
         }else {
             if (r.getMsg() != null){
                 return r;
             }
         }
         return R.ok("修改成功!");
     }

    /**
     * 返回流水和新增流水
     * @param bid 发货单bid
     * @return
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R recalculateFlow(String bid) throws Exception {
        try {
            TccFbaDeliver tccFbaDeliver1 = new TccFbaDeliver().setBid(bid).queryFirst();
            if (tccFbaDeliver1 == null){
                return R.error("发货单不存在,请核实后再操作!");
            }
            List<TccLogisticsMethodItem> tdjzPrice;
            BigDecimal jfStart = BigDecimal.ZERO;
            BigDecimal jfEnd = BigDecimal.ZERO;
            BigDecimal jfFee = BigDecimal.ZERO;

            logger.info("-----返回发货单流水开始-----");

            Date dshsj = null;
            if (tccFbaDeliver1.getRecalculateTime() != null){
                dshsj = tccFbaDeliver1.getRecalculateTime();
            }else {
                dshsj = tccFbaDeliver1.getAuditingTime();
            }

            Date auditingTime = new Date();

            List<TcwAccountDetailedForCompany> list = new TcwAccountDetailedForCompany().setMbid(bid).setDshsj(dshsj)
                    .where("A.vbz NOT LIKE '%物流服务变更%' ")
                    .queryList();
            for(TcwAccountDetailedForCompany item:list) {
                System.out.println(item.getVgsbm() + ":" + item.getFje());
                if ("物流服务→头程运费".equals(item.getVjylx())) {
                    tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
                            item.getVgsbm(), item.getVgsjc(),
                            item.getVgsbmp(), item.getVgsjcp(),
                            item.getVjylx(),
                            BigDecimal.ZERO.subtract(item.getFje()),
                            item.getDjysj(),
                            auditingTime,
                            "物流服务变更(特殊) - " + item.getVbz(),
                            item.getMbid(), item.getWriteTime());
                }
            }
            logger.info("-----返回发货单流水结束-----");


            //计划单
            TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(tccFbaDeliver1.getFbaPlanBid()).queryFirst();

//            //计划子件
//            List<TccFbaPlanItem> tccFbaPlanItemList = new TccFbaPlanItem().setBidFbaPlan(tccFbaPlan.getBid()).queryList();
//
//            //店铺信息
//            TpAmazonShop tpAmazonShop = new TpAmazonShop().setId(tccFbaPlan.getShopId()).queryFirst();
//
//            //查询所有的发货单FBA信息
//            List<TccFbaDeliverItem> tccFbaDeliverItemListOld = new TccFbaDeliverItem().setFbaPlanBid(tccFbaPlan.getBid()).queryList();
//
//            //查询所有发货单的箱子信息
//            List<TccFbaDeliverSon> tccFbaDeliverSonListOld = new TccFbaDeliverSon().setFbaPlanBid(tccFbaPlan.getBid()).queryList();
//            //查询箱子对应的实际商品数据
//            List<TccFbaBoxDetail> tccFbaBoxDetailListOld = new TccFbaBoxDetail().setBidFbaPlan(tccFbaPlan.getBid()).queryList();
//            //箱子商品信息
//            List<TccFbaBoxUpItem> tccFbaBoxUpItemListOld = new TccFbaBoxUpItem().setBidFbaPlan(tccFbaPlan.getBid()).queryList();

            TccFbaFeeDetails tccFbaFeeDetailsNew = new TccFbaFeeDetails().setSourceType(TccFbaFeeDetailsEnum.SourceType.DELIVER.value).setSourceBid(tccFbaDeliver1.getBid()).queryFirst();
            R r = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
                    tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(), "GS0899", "物流部（中间账户）",
                    "物流服务→头程运费", tccFbaFeeDetailsNew.getPriceTranPredict().negate(), tccFbaDeliver1.getCreateTime(), auditingTime,
                    "FBA计划单号:" + tccFbaPlan.getBid() + "，FBA发货单号:" + tccFbaDeliver1.getBid(),
                    tccFbaDeliver1.getBid(), auditingTime);
            if (r.getCode() != 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return R.error(r.getMsg());
            }

            r = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
                    "GS0899", "物流部（中间账户）", tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(),
                    "物流服务→头程运费", tccFbaFeeDetailsNew.getPriceTranPredict(), tccFbaDeliver1.getCreateTime(), auditingTime,
                    "FBA计划单号:" + tccFbaPlan.getBid() + "，FBA发货单号:" + tccFbaDeliver1.getBid(),
                    tccFbaDeliver1.getBid(), auditingTime);
            if (r.getCode() != 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return R.error(r.getMsg());
            }
//
//            //箱子数量
//            Integer boxNum = 0;
//            BigDecimal boxNumPrice = BigDecimal.ZERO;
//            //透明标
//            Integer tagTransparentNum = 0;
//            BigDecimal tagTransparentPrice = BigDecimal.ZERO;
//            Map<String, Integer> transparentReMap = new HashMap<>();
//            String finaltagTransparentRe = "";
//            //欧代标
//            Integer tagEurNum = 0;
//            BigDecimal tagEurPrice = BigDecimal.ZERO;
//            Map<String, Integer> tagEurMap = new HashMap<>();
//            String finaltagEurRe = "";
//
//            //收取标签费用/箱子费用
//            List<TccFbaDeliverItem> tccFbaDeliverItemList = tccFbaDeliverItemListOld.stream()
//                    .filter(tccFbaDeliverItem -> tccFbaDeliverItem.getPbid().equals(tccFbaDeliver1.getBid()))
//                    .collect(Collectors.toList());
//            for (TccFbaDeliverItem tccFbaDeliverItem : tccFbaDeliverItemList) {
//                List<TccFbaDeliverSon> tccFbaDeliverSonList = tccFbaDeliverSonListOld.stream()
//                        .filter(tccFbaDeliverSon -> tccFbaDeliverSon.getFbaDeliverItemId().equals(tccFbaDeliverItem.getId()))
//                        .collect(Collectors.toList());
//                for (TccFbaDeliverSon tccFbaDeliverSon : tccFbaDeliverSonList) {
//                    boxNum = boxNum + 1;
//                    //查询箱子对应的实际商品数据
//                    List<TccFbaBoxDetail> tccFbaBoxDetailList = tccFbaBoxDetailListOld.stream()
//                            .filter(tccFbaBoxDetail -> tccFbaBoxDetail.getBoxId().equals(tccFbaDeliverSon.getFbaBoxId()))
//                            .collect(Collectors.toList());
//                    for (TccFbaBoxDetail tccFbaBoxDetail : tccFbaBoxDetailList) {
//                        List<TccFbaBoxUpItem> tccFbaBoxUpItemList = tccFbaBoxUpItemListOld.stream()
//                                .filter(tccFbaBoxUpItem -> tccFbaBoxUpItem.getId().equals(tccFbaBoxDetail.getBoxUpItemId()))
//                                .collect(Collectors.toList());
//                        TccFbaBoxUpItem tccFbaBoxUpItem = tccFbaBoxUpItemList.get(0);
//                        List<TccFbaPlanItem> tccFbaPlanItemListNew = tccFbaPlanItemList.stream()
//                                .filter(tccFbaPlanItem -> tccFbaPlanItem.getId().equals(tccFbaBoxUpItem.getFbaPlanItemId()))
//                                .collect(Collectors.toList());
//                        TccFbaPlanItem tccFbaPlanItem = tccFbaPlanItemListNew.get(0);
//                        //透明标
//                        if (tccFbaPlanItem.getIsSign().equals("是")) {
//                            if (transparentReMap.get(tccFbaPlanItem.getCommodityCode()) == null) {
//                                transparentReMap.put(tccFbaPlanItem.getCommodityCode(), tccFbaBoxDetail.getNum());
//                                tagTransparentNum = tagTransparentNum + tccFbaBoxDetail.getNum();
//                            } else {
//                                Integer transparentRe = transparentReMap.get(tccFbaPlanItem.getCommodityCode());
//                                tagTransparentNum = tagTransparentNum + tccFbaBoxDetail.getNum();
//                                transparentReMap.put(tccFbaPlanItem.getCommodityCode(), transparentRe);
//                            }
//                        }
//                        //判断店铺欧代标是否需要打印
//                        if (tpAmazonShop.getEuStatus() == 1) {
//                            if (tagEurMap.get(tccFbaPlanItem.getCommodityCode()) == null) {
//                                tagEurMap.put(tccFbaPlanItem.getCommodityCode(), tccFbaBoxDetail.getNum());
//                                tagEurNum = tagEurNum + tccFbaBoxDetail.getNum();
//                            } else {
//                                Integer transparentRe = tagEurMap.get(tccFbaPlanItem.getCommodityCode());
//                                tagEurNum = tagEurNum + tccFbaBoxDetail.getNum();
//                                tagEurMap.put(tccFbaPlanItem.getCommodityCode(), transparentRe);
//                            }
//
//                        }
//                    }
//                }
//            }
//
//            //纸箱费
//            boxNumPrice = new BigDecimal(boxNum).multiply(new BigDecimal(15)).setScale(2, BigDecimal.ROUND_HALF_UP);
//
//            r = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
//                    tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(), "GS0608", "仓储部",
//                    "仓储服务→纸箱费", boxNumPrice.negate(), tccFbaDeliver1.getCreateTime(), auditingTime,
//                    "FBA计划单号:" + tccFbaPlan.getBid() + "，FBA发货单号:" + tccFbaDeliver1.getBid() + ",箱子数量:" + boxNum + "个",
//                    tccFbaDeliver1.getBid(), auditingTime);
//            if (r.getCode() != 0) {
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                return R.error(r.getMsg());
//            }
//
//            r = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
//                    "GS0608", "仓储部", tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(),
//                    "仓储服务→纸箱费", boxNumPrice, tccFbaDeliver1.getCreateTime(), auditingTime,
//                    "FBA计划单号:" + tccFbaPlan.getBid() + "，FBA发货单号:" + tccFbaDeliver1.getBid() + ",箱子数量:" + boxNum + "个",
//                    tccFbaDeliver1.getBid(), auditingTime);
//            if (r.getCode() != 0) {
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                return R.error(r.getMsg());
//            }
//
//            //透明计划贴标费
//            if (tagTransparentNum != 0) {
//
//                tagTransparentPrice = new BigDecimal(tagTransparentNum).multiply(new BigDecimal(0.6)).setScale(2, BigDecimal.ROUND_HALF_UP);
//
//                //备注
//                for (Map.Entry<String, Integer> entry : transparentReMap.entrySet()) {
//                    finaltagTransparentRe = finaltagTransparentRe + "商品编码:" + entry.getKey() + ",数量:" + entry.getValue() + ",";
//                }
//
//                r = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
//                        tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(), "GS0608", "仓储部",
//                        "仓储服务→透明计划贴标费", tagTransparentPrice.negate(), tccFbaDeliver1.getCreateTime(), auditingTime,
//                        "FBA计划单号:" + tccFbaPlan.getBid() + "，FBA发货单号:" + tccFbaDeliver1.getBid() + "," + "透明标:" + tagTransparentNum + "个",
//                        tccFbaDeliver1.getBid(), auditingTime);
//                if (r.getCode() != 0) {
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    return R.error(r.getMsg());
//                }
//
//                r = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
//                        "GS0608", "仓储部", tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(),
//                        "仓储服务→透明计划贴标费", tagTransparentPrice, tccFbaDeliver1.getCreateTime(), auditingTime,
//                        "FBA计划单号:" + tccFbaPlan.getBid() + "，FBA发货单号:" + tccFbaDeliver1.getBid() + "," + "透明标:" + tagTransparentNum + "个",
//                        tccFbaDeliver1.getBid(), auditingTime);
//                if (r.getCode() != 0) {
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    return R.error(r.getMsg());
//                }
//            }
//
//            //欧代标费用
//            if (tagEurNum != 0) {
//
//                tagEurPrice = new BigDecimal(tagEurNum).multiply(new BigDecimal(0.6)).setScale(2, BigDecimal.ROUND_HALF_UP);
//
//                //备注
//                for (Map.Entry<String, Integer> entry : tagEurMap.entrySet()) {
//                    finaltagEurRe = finaltagEurRe + "商品编码:" + entry.getKey() + ",数量:" + entry.getValue() + ",";
//                }
//
//                r = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
//                        tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(), "GS0608", "仓储部",
//                        "仓储服务→欧代贴标费", tagEurPrice.negate(), tccFbaDeliver1.getCreateTime(), auditingTime,
//                        "FBA计划单号:" + tccFbaPlan.getBid() + "，FBA发货单号:" + tccFbaDeliver1.getBid() + "," + "欧代标:" + tagEurNum,
//                        tccFbaDeliver1.getBid(), auditingTime);
//                if (r.getCode() != 0) {
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    return R.error(r.getMsg());
//                }
//
//                r = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
//                        "GS0608", "仓储部", tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(),
//                        "仓储服务→欧代贴标费", tagEurPrice, tccFbaDeliver1.getCreateTime(), auditingTime,
//                        "FBA计划单号:" + tccFbaPlan.getBid() + "，FBA发货单号:" + tccFbaDeliver1.getBid() + "," + "欧代标:" + tagEurNum,
//                        tccFbaDeliver1.getBid(), auditingTime);
//                if (r.getCode() != 0) {
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    return R.error(r.getMsg());
//                }
//            }


            tccFbaDeliver1.setRecalculateTime(auditingTime);
//            tccFbaDeliver1.setTransparentNum(tagTransparentNum);
//            tccFbaDeliver1.setEurNum(tagEurNum);
//            tccFbaDeliver1.setBoxNum(boxNum);
            tccFbaDeliverMapper.update(tccFbaDeliver1);
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(e.getCause().getMessage());
        }
        return R.ok();
    }
}
